package _switch;

import org.junit.Test;

/**
 * 传统switch声明语句的弊端：
 * case穿透：匹配时自上而下的，如忘记写break，后面的case语句不论匹配与否都会执行。
 * 所有的case语句共用一个块范围，在不同的case语句定义的变量名不能重复。
 * 不能在一个case里写多个执行结果一致的条件；
 * 整个switch不能作为表达式返回值
 */
public class SwitchTest {
    @Test
    public void test1() {
        Week day = Week.SATURDAY;
        switch (day) {
            case MONDAY:
            case TUESDAY:
            case WEDNESDAY:
            case THURSDAY:
            case FRIDAY:
                System.out.println("工作");
                break;
            case SATURDAY:
            case SUNDAY:
                System.out.println("休息");
                break;
            default:
                System.out.println("异常");
        }

    }

    @Test
    public void test2() {
        Week day = Week.FRIDAY;
        switch (day) {
            case MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY -> System.out.println("上班");
            case SATURDAY, SUNDAY -> System.out.println("休息");
            default -> System.out.println("异常");
        }
    }

    @Test
    public void test3() {
        Week day = Week.WEDNESDAY;
        System.out.println(day.ordinal());
        int v = (int) (Math.random() * 7 + 1);
        boolean isWork = switch (day) {
            case MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY -> {
                System.out.println("You need working...");
                yield true;
            }
            case SATURDAY, SUNDAY -> false;
        };

        System.out.println(isWork);
    }

    static String formatter(Object o) {
        if (o instanceof Integer integer) {
            return "int " + integer;
        } else if (o instanceof Long l) {
            return "long " + l;
        } else if (o instanceof Double d) {
            return "double " + d;
        } else if (o instanceof String s) {
            return "String " + s;
        }
        return "unknown";
    }

    /**
     * 以上方法改写为使用 switch 结构
     * JDK17 预览特性
     */
//    static String formatterSwitch(Object o) {
//        return switch (o) {
//            case Integer i -> "int " + i;
//            case Double d -> "double " + d;
//            case Long l -> "long " + l;
//            case String s -> "String " + s;
//            default -> "null";
//        };
//    }
    @Test
    public void test4() {
        System.out.println(formatter(new Object()));
//        System.out.println(formatterSwitch(new String("asd")));
    }
}
